<template>
  <MainLayout title="手动填报">
    <!-- 顶部信息 + 右上角导入按钮（NEW） -->
    <view class="head">
      <view class="title">
        <view>项目：{{ form?.projectName || '-' }}</view>
        <view>任务：{{ form?.taskName || '-' }}</view>
      </view>
      <button class="btn import" @click="onImport">导入设备数据</button>

      <!-- item 卡片 -->
      <view class="item-card" v-for="it in form?.items || []" :key="it.keyPrefix">
        <!-- 右上角角标：仅在重新采集时显示 -->
        <view v-if="it.resample" class="resample-badge">重新采集</view>
        <view class="item-title">
          {{ it.title }}
<!--          <text v-if="it.resample" class="badge-red">重新采集</text> &lt;!&ndash; ★ 右上角红标 &ndash;&gt;-->
<!--          <text v-if="it.resample" class="badge-red">重新采集</text>-->
        </view>

        <!-- 设计要求 + 最小抽样数量 + 检验批部位 -->
        <view class="item-require">
          <view class="kv"><text class="k">设计要求</text><text class="v">{{ it.require || '-' }}</text></view>
          <view class="kv"><text class="k">最小抽样数</text><text class="v">{{ it.minNumber ?? '-' }}</text></view>
          <view class="kv" v-if="t(it) !== 3">
            <text class="k">检验批部位</text><text class="v">{{ it.taskLocation || '-' }}</text>
          </view>
        </view>

        <!-- 采集人（所有类型都显示，可编辑） -->
        <view class="row">
          <text class="label">采集人</text>
          <input class="ipt" v-model="it.collector" placeholder="请输入工长姓名"/>
        </view>

        <!-- === 以下保持你三类表单 === -->

        <template v-if="t(it) === 1">
          <view class="row">
            <text class="label">是否合格</text>
            <picker :range="directOptions" @change="e => onDirectPick(it, e.detail.value,it.title)">
              <view class="picker">{{ it.result || '请选择' }}</view>
            </picker>
          </view>
          <view class="row">
            <text class="label">验收记录</text>
            <textarea v-model="it.record" placeholder="选择是否合格后自动生成，可修改"/>
          </view>
        </template>

        <template v-else-if="t(it) === 2">
          <view class="row">
            <text class="label">实际抽样数</text>
            <input class="ipt" type="number" v-model.number="it.number" @input="onRateInput(it)" placeholder="请输入"/>
          </view>
          <view class="row">
            <text class="label">合格数</text>
            <input class="ipt" type="number" v-model.number="it.passCount" @input="onRateInput(it)" placeholder="请输入"/>
          </view>
          <view class="row">
            <text class="label">合格率</text>
            <input class="ipt" :value="it.passRate || ''" disabled />
          </view>
          <view class="row">
            <text class="label">验收记录</text>
            <textarea v-model="it.record" placeholder="将按数量与合格数自动生成，可修改"/>
          </view>
        </template>

        <template v-else-if="t(it) === 3">
          <view class="row">
            <text class="label">实际抽样数</text>
            <input class="ipt" :value="it.number ?? ''" disabled />
          </view>
          <view class="row">
            <text class="label">验收情况记录</text>
            <textarea :value="it.record || ''" disabled />
          </view>
        </template>

        <!-- 附件 -->
        <view class="row" v-if="it.hasPhoto || it.hasPdf">
          <text class="label">附件</text>
          <view>
            <button v-if="it.hasPhoto && !it.readOnly" class="btn" @click="upload('photo', it)">上传照片</button>
            <button v-if="it.hasPdf && !it.readOnly" class="btn" @click="upload('pdf', it)">上传PDF</button>
            <text v-if="it.readOnly" class="tip">（设备导入项不可编辑）</text>
          </view>
        </view>
      </view>

      <!-- 底部操作（NEW） -->
      <view class="actions">
        <button class="btn ghost" @click="backConfirm">返回</button>
        <button class="btn ghost" @click="save">暂存</button>
        <button class="btn primary" @click="submit">提交</button>
      </view>
    </view>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { api } from '@/services/api'
import MainLayout from '@/layouts/MainLayout.vue'

const form = ref<any>(null)
const taskId = ref<number>(0)
const taskType = ref<string>('')

onLoad((opts:any)=>{
  taskId.value = Number(opts?.id || 0)
  taskType.value = String(opts?.type || '')
  if (!taskId.value) { uni.showToast({ title:'任务ID缺失', icon:'none' }); return }
  load()
})

async function load(){
  form.value = await api.getManualForm(taskId.value)
}

/** 将类似 "≥6" 或 "6 套" 的最小抽样数量转成数字对比用 */
function parseMinNumber(min: any): number | undefined {
  if (min === null || min === undefined || min === '') return undefined
  const str = String(min)
  const m = str.match(/\d+/)
  return m ? Number(m[0]) : undefined
}

/** 1) 实际抽样数量 < 最小抽样数量 时提醒（输入框 blur 触发 & 提交前也会二次校验） */
function checkMin(it:any) {
  const min = parseMinNumber(it.minNumber)
  if (min !== undefined) {
    const num = Number(it.number)
    if (Number.isFinite(num) && num < min) {
      uni.showModal({
        title: '提醒',
        content: `${it.title} 的“实际抽样数量”(${num}) 小于“最小抽样数量”(${min})，请确认是否继续。`,
        showCancel: true
      })
    }
  }
}

/** 2) 右上角：导入设备数据（占位） */
async function onImport(){
  try {
    await api.importDeviceData?.(taskId.value)  // 后端未实现会抛错，下面兜底提示
    // 如果后端返回了结构，可在这里把返回的数据合并到 form.value.items
    uni.showToast({ title:'已从设备导入', icon:'success' })
  } catch (e) {
    uni.showToast({ title:'设备接口暂未接入（占位）', icon:'none' })
  }
}

async function save(){
  await api.saveManualForm(taskId.value, taskType.value, { items: form.value.items })
  uni.showToast({ title:'保存成功', icon:'success' })
  setTimeout(()=>uni.navigateBack(), 400)
}

async function upload(kind:'photo'|'pdf', it:any){
  const choose = await uni.chooseImage({ count:1 })
  const filePath = choose.tempFilePaths[0]
  const { url } = await api.uploadFile(filePath, kind)
  if (kind==='photo') it.photoUrl = url
  else it.pdfUrl = url
}


// 统一将 itemType 转成数字；为空时当 1（直接观察）
const t = (it: any) => Number(it?.itemType ?? 1)

// 直接观察类下拉选项（可复用）
const directOptions = ['合格', '不合格']


/** 直接观察类：选择“是否合格”后自动生成记录 */
async function onDirectPick(it:any, idx:number, taskType:string) {
  const val = ['合格','不合格'][Number(idx)] || ''
  it.result = val
  if (!val) { it.record = ''; return }

  const fallback = `经直接观察，判定为：${val}`

  try {
    const itemKey = it.keyPrefix || it.inspect_item || it.item_en || ''
    const tpl = await api.getRecordTemplateByItem(itemKey)
    if (typeof tpl === 'string' && tpl.trim()) {
      const ctx:any = { result: val, item_name: it.title || '', position: it.position || '' }
      it.record = tpl.replace(/\$\{(\w+)\}/g, (_:any, k:string) => (ctx[k] ?? ''))
    } else {
      it.record = fallback
    }
  } catch {
    it.record = fallback
  }
}



/** 观察合格率类：实时计算合格率与记录 */
function onRateInput(it:any) {
  const n = Number(it.number)
  const p = Number(it.passCount)
  if (Number.isFinite(n) && n > 0 && Number.isFinite(p) && p >= 0) {
    const pct = Math.max(0, Math.min(100, Math.round((p*100)/n)))
    it.passRate = pct + '%'
    it.record = `实抽${n}件，合格${p}件，合格率${pct}%`
  } else {
    it.passRate = ''
    // 不覆盖用户手填的记录
  }
}


/** 返回确认（NEW） */
function backConfirm(){
  uni.showModal({
    title: '确认返回',
    content: '未保存的数据将丢失，确认要返回吗？',
    success: (res) => { if (res.confirm) uni.navigateBack() }
  })
}

/** 表单校验（提交时用） */
function validate(): { ok:boolean; msg?:string } {
  if (!form.value || !Array.isArray(form.value.items)) return { ok:false, msg:'表单未加载' }

  for (const it of form.value.items) {
    const label = it.title || it.keyPrefix
    // 必填：number/record/result
    if (it.number === undefined || it.number === null || String(it.number) === '') {
      return { ok:false, msg:`请填写「${label}」的 实际抽样数量` }
    }
    if (!it.record || !String(it.record).trim()) {
      return { ok:false, msg:`请填写「${label}」的 检查记录` }
    }
    if (!it.result || !String(it.result).trim()) {
      return { ok:false, msg:`请填写「${label}」的 检查结果` }
    }
    // 与最小抽样数量的硬性校验
    const min = parseMinNumber(it.minNumber)
    if (min !== undefined && Number(it.number) < min) {
      return { ok:false, msg:`「${label}」的 实际抽样数量 不能小于 最小抽样数量（${min}）` }
    }
  }
  return { ok:true }
}

/** 3) 提交：先校验 → 保存到数据库 → 占位发送上游 */
async function submit(){
  const v = validate()
  if (!v.ok) { uni.showToast({ title: v.msg!, icon:'none', duration: 2200 }); return }

  try {
    await api.saveManualForm(taskId.value, taskType.value, { items: form.value.items })
  } catch (e) {
    uni.showToast({ title:'保存失败', icon:'none' })
    return
  }

  // 占位：向上游系统发送（后端未实现也不影响保存）
  try {
    await api.pushUpstream?.(taskId.value, taskType.value, { items: form.value.items })
  } catch {
    // 不中断流程，只提示占位
    uni.showToast({ title:'已保存，本地成功；上游发送暂未接入', icon:'none' })
    setTimeout(()=> uni.navigateBack(), 600)
    return
  }

  uni.showToast({ title:'提交成功', icon:'success' })
  setTimeout(()=> uni.navigateBack(), 600)
}

</script>

<style scoped>
.wrap{padding:12px}
.head{display:grid;gap:6px;margin-bottom:10px}
.table{display:grid;grid-template-columns:1.2fr 2.2fr .9fr .9fr .9fr 2fr 1.1fr 1.3fr;gap:8px;align-items:start}
.header{font-weight:600;color:#222;margin-bottom:8px}
.row{background:#fff;border-radius:8px;padding:10px;box-shadow:0 1px 3px rgba(0,0,0,.05);margin-bottom:10px}
.ipt{border:1px solid #eee;border-radius:6px;padding:6px;background:#fff;width:100%}
.attach .btn{padding:6px 10px;border:1px solid #e6e6e6;border-radius:6px;background:#fff;font-size:12px;margin-right:6px}
.actions{display:flex;justify-content:flex-end;margin-top:12px}
.primary{background:#1677ff;color:#fff;border:0;border-radius:8px;padding:8px 14px}
.item-card{background:#fff;border-radius:10px;padding:12px;margin:10px 12px;box-shadow:0 1px 3px rgba(0,0,0,.05)}
.item-title{font-weight:600;margin-bottom:8px}
.row{display:flex;align-items:center;gap:10px;margin:8px 0}
.label{width:90px;color:#666}
.ipt{flex:1;border:1px solid #eee;border-radius:6px;padding:6px}
.picker{flex:1;border:1px solid #eee;border-radius:6px;padding:8px;color:#333;background:#fff}
.tip{color:#999;font-size:12px;margin-left:8px}
.item-require{display:grid;grid-template-columns:repeat(3,1fr);gap:8px 14px;margin:6px 0 8px}
.kv{display:flex;gap:6px;color:#555;align-items:center}
.k{color:#888;min-width:80px}
.v{color:#333}
.badge-red{color:#ff4d4f;font-size:12px;margin-left:8px}
.item-card{
  position: relative;            /* 让角标以卡片为定位容器 */
  background:#fff;
  border-radius:10px;
  padding:12px;
  margin:10px 12px;
  box-shadow:0 1px 3px rgba(0,0,0,.05);
}

/* 圆角 pill 样式的右上角标 */
.resample-badge{
  position:absolute;
  top:8px;
  right:10px;
  padding:2px 8px;
  font-size:12px;
  line-height:18px;
  color:#ff4d4f;
  background:#fff1f0;           /* 淡红背景 */
  border:1px solid #ffccc7;     /* 淡红描边 */
  border-radius:999px;          /* 胶囊形 */
  font-weight:600;
}

</style>
